/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kiff.util.transaction;

import javax.persistence.EntityManager;

import kiff.util.ContextManager;
import kiff.util.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

/**
 * EntityManager Transaction Wrapper Provider.
 * @author Adam
 * @version $Id: EntityManagerTransactionProvider.java 62 2008-10-31 04:51:50Z a.ruggles $
 * 
 * Created on Oct 9, 2008 at 1:00:23 PM 
 */
public class EntityManagerTransactionProvider implements Provider<Transaction> {

	/**
	 * Entity Manager, used to get the Entity Transaction.
	 */
	private final EntityManager entityManager;

	/**
     * The <code>Logger</code> is used by the application to generate a log messages.
     */
    private final Logger logger = LoggerFactory.getLogger(EntityManagerTransactionProvider.class);

    /**
	 * Constructs a EntityMananger Transaction Provider.
	 * @param entityManager the Entity Manager.
	 */
	@Inject
	public EntityManagerTransactionProvider(final EntityManager entityManager) {
		if (entityManager == null) {
			throw new IllegalArgumentException("Entity Mananger cannot be null");
		}
		this.entityManager = entityManager;
	}

	/**
	 * {@inheritDoc}
	 * @see kiff.util.Provider#get()
	 */
	public Transaction get() {
		Transaction tx = ContextManager.getBind(Transaction.class);
		if (tx == null) {
			tx = new EntityManagerTransaction(entityManager);
			logger.debug("Binding new Transaction [{}]", tx);
			ContextManager.bind(Transaction.class, tx);
		}
		return tx;
	}
}
